﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP
{
    /// <summary>CCPSIP_003：推播通知 Token 上傳 API</summary>
    /// idHeader = 裝置 UUID 前八碼。iOS 請使用 [CCPCrypto getIdHeader] 呼叫。
    /// checkcode = 裝置限時驗證碼。iOS 請使用 [CCPCrypto getCheckcode] 呼叫。
    /// deviceToken = 註冊 Device 的 APNs Token 或 GCM Registration ID。
    /// devEnv = App 是否為開發版本，是為 'Y'，否則 'N'。

    public class push_token_upload : IHttpHandler
    {
        private static string[] kAdminEmailList = { "ch_chou@ccp.com.tw", "hj_huang@ccp.com.tw",
                                                "mike_lin@ccp.com.tw", "chuck_lan@ccp.com.tw"
                                              };
        private const string kReportEmailAddr = "ccpsip_report@ccp.com.tw";


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string deviceToken = req.Form["deviceToken"];//Device Push Token
                string devEnv = req.Form["devEnv"];//是否為開發測試版

                try
                {
                    deviceToken = deviceToken.Trim();
                }
                catch
                {
                    throw new Exception("Error_01: Parameter Error");//參數錯誤
                }

                string PushType = PushKit.ToPushType(devEnv, deviceToken);


                //【01-1】檢查deviceToken參數長度
                //
                if (deviceToken.Length > 255)
                {
                    Dictionary<string, string> paramDict = new Dictionary<string, string>();
                    paramDict["idHeader"] = idHeader;
                    paramDict["deviceToken"] = deviceToken;
                    paramDict["devEnv"] = devEnv;
                    string emailBody = ChrisKit.DictToJSON(paramDict, true);
                    ChrisKit.SendCCPEmail(kReportEmailAddr, kAdminEmailList, null, "【通報】iSender Push Token 長度警告", emailBody);
                    throw new Exception("Error_91: Push token exceeded max length");
                }


                //【02】檢查註冊裝置
                //
                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    string DeviceUUID = OracleKitReg.getAuthUUID(idHeader, checkcode);
                    if (string.IsNullOrEmpty(DeviceUUID))
                    {
                        throw new Exception("Error_02: Cannot identify this device");//無法識別此裝置
                    }
                    else
                    {
                        string ApplyStatus = OracleKitReg.getApplyStatus(DeviceUUID);
                        if (ApplyStatus != "1")
                        {
                            throw new Exception("Error_03: Register status is wrong");//註冊狀態錯誤
                        }

                        //【03-1】更新Device Push Token(待確認區)
                        //
                        OracleKitReg.UpdateRegAuthDevice(DeviceUUID, deviceToken, PushType);
                    }
                }
                else
                {
                    //【03-2】更新Device Push Token
                    //
                    OracleKitUser.UpdateDeviceToken(userInfo.UUID, deviceToken, PushType);
                }

                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
